<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <el-input v-model="query.title" clearable placeholder="输入搜索标题" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
      <el-input v-model="query.japanese" clearable placeholder="输入搜索子标题" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
      <el-input v-model="query.serialNumber" clearable placeholder="输入搜索序列号" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
      <el-input v-model="query.phone" clearable placeholder="输入搜索绑定手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />

      <el-select v-model="query.status" clearable placeholder="请选中状态" class="filter-item" style="width: 200px">
        <el-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <el-select v-model="query.color" clearable placeholder="请选中颜色" class="filter-item" style="width: 200px">
        <el-option v-for="item in colorList" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>

      <!-- <el-input v-model="query.productName" clearable placeholder="输入搜索产品名称" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" /> -->


      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
      <!-- 新增 -->
      <!-- <el-button
        v-permission="['admin','atBusiness:add']"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >新增</el-button> -->
      <el-button
        type="danger"
        class="filter-item"
        size="mini"
        icon="el-icon-refresh"
        @click="toQuery"
      >刷新</el-button>
      <el-button
        type="danger"
        class="filter-item"
        size="mini"
        icon="el-icon-refresh"
        @click="batchDelete"
      >删除</el-button>
      <el-button
        type="danger"
        class="filter-item"
        size="mini"
        icon="el-icon-refresh"
        @click="toDownloadClick"
      >导出</el-button>

      <!--表单组件-->
      <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="title" width="800px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="150px">

         <el-form-item label="卡片名称">
           <el-input v-model="form.title" style="width: 370px;" disabled/>
         </el-form-item>

          <el-form-item label="序列号" >
            <el-input v-model="form.serialNumber" style="width: 370px;" disabled/>
          </el-form-item>
          <el-form-item label="颜色">
            <el-select v-model="form.color" clearable placeholder="请选中颜色" class="filter-item" style="width: 370px" disabled>
              <el-option v-for="item in colorList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="颜色2">
            <el-input v-model="form.japanese" style="width: 370px;" disabled/>
          </el-form-item>
          <el-form-item label="绑定用户">
            <el-select v-model="form.userId" clearable filterable placeholder="请选中绑定用户" class="filter-item" style="width: 370px">
              <el-option v-for="item in userList" :key="item.uid" :label="item.nickname" :value="item.uid" />
            </el-select>
            <div><span style="color: red;">选中用户代表已绑定用户，删除用户代表未绑定</span></div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancel">取消</el-button>
          <el-button :loading="loading" type="primary" @click="submit">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table v-loading="loading" :data="data" size="small" style="width: 100%;" @selection-change="handleSelectionChange">
       <el-table-column type="selection" width="55" />
         <el-table-column type="index" width="55" label="序号">
             <template scope="scope">
               <span>{{((page+1) - 1) * size + scope.$index + 1}}</span>
               </template>
           </el-table-column>
        <el-table-column  prop="title" label="卡片名称">
        </el-table-column>
        <el-table-column  prop="mainUrl" label="主图">
          <template slot-scope="scope">
                 <el-image
                       style="width: 80px; height: 80px"
                       :src="scope.row.mainUrl"
                       :preview-src-list="[scope.row.mainUrl]"
                     ></el-image>
              </template>
        </el-table-column>
       
        </el-table-column>
        <el-table-column  prop="japanese" label="颜色2" />
        <el-table-column prop="serialNumber" label="序列号" />
        <el-table-column  prop="levelFactoryDate" label="出厂时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.levelFactoryDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column  prop="color" label="颜色" />
        <el-table-column prop="status" label="状态" >
           <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" style="cursor: pointer;background-color: red;color: white;" :type="'info'">待登记</el-tag>
            <el-tag v-if="scope.row.status === 1" style="cursor: pointer;background-color: green;color: white;" :type="'info'">已登记</el-tag>
          </template>
        </el-table-column>
        <el-table-column  prop="r" label="拥有人信息" width="300">
             <template slot-scope="scope">
                 <div style="display: flex;flex-direction: row;align-items: center;" v-if="scope.row.status==1">
                      <img :src="scope.row.yxUser.avatar" style="width: 50px;height: 50px;border-radius: 25px;" v-if="scope.row.yxUser"/>
                      <span style="margin-left: 10px;" v-if="scope.row.yxUser" >{{scope.row.yxUser.nickname}}-{{scope.row.phone}}</span>
                 </div>
             </template>
        </el-table-column>
         <el-table-column  prop="points" label="积分" >
           <template slot-scope="scope">
               <span>{{formatPoints(scope.row.points)}}</span>
            </template>
          </el-table-column>
        <el-table-column  prop="bandTime" label="绑定时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.bandTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column  prop="remark" label="备注" />

        <el-table-column  prop="createTime" label="添加时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column  prop="updateTime" label="更新时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','atBusiness:edit','atBusiness:del']" label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="edit(scope.row)"
            >
              绑定登记人
            </el-button>
            <el-popover
              :ref="scope.row.id"
              placement="top"
              width="180"
            >
              <p>确定删除本条数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
              </div>
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>
 import initData from '@/mixins/crud'
  import checkPermission from '@/utils/permission'
  import { add, edit,del,send,toDownload } from '@/api/hcsCardRecord'
  import {getList} from '@/api/hcsProduct'
  import {getAllUserList} from '@/api/yxUser'
   import { parseTime, downloadFile } from '@/utils/index'


// crud交由presenter持有
export default {
   mixins: [initData],
  data() {
    return {
      userList:[],
      isAdd:true,
       loading: false, dialog: false,
       delLoading: false,
       title:"新增",
       productList:[],
       colorList:[
         {name:'原色',value:"原色"}, {name:'异色',value:"异色"}, {name:'特殊色',value:"特殊色"}
       ],
       statusList:[
         {name:'未登记',value:0}, {name:'已登记',value:1}
       ],
       multipleSelection:[],
       form:{
         id: '',
         title :"",
         japanese: "",
         userId:'',
         serialNumber:"",
         levelFactoryDate :"",
         color: "",
         status:1,
         remark :""
      },
      permission: {
        add: ['admin', 'hcsCardRecord:add'],
        edit: ['admin', 'hcsCardRecord:edit'],
        del: ['admin', 'hcsCardRecord:del']
      },
      rules: {
      }
       }
  },
  watch: {
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
     this.initProduct(),
     this.initUser()
  },

  methods: {
   checkPermission,
   beforeInit() {
     this.url = 'api/hcsCardRecord'
     const sort = 'id,desc'
     this.params = { page: this.page, size: this.size, sort: sort }
     return true
   },
handleSelectionChange(selection){
  this.multipleSelection = selection; 
},
   add(){
     this.dialog = true
     this.isAdd = true
     // this.resetForm()

     // this.initProduct()
   },
   batchDelete(){
     if (this.multipleSelection.length === 0) {
         this.$message.warning('请选择至少一项进行删除');
         return;
       }
      const idsToDelete = this.multipleSelection.map(item => item.id);
      del(idsToDelete).then(res => {
         console.log(res)
         this.$notify({
           title: '删除成功',
           type: 'success',
           duration: 2500
         })
         this.loading = false
         this.init()
     }).catch(err => {

     })
      
   },
   toDownloadClick(){
     let params = [];
     if (this.query.phone) params.push("phone=" + encodeURIComponent(this.query.phone));
     if (this.query.japanese) params.push("japanese=" + encodeURIComponent(this.query.japanese));
     if (this.query.title) params.push("title=" + encodeURIComponent(this.query.title));
     if (this.query.serialNumber) params.push("serialNumber=" + encodeURIComponent(this.query.serialNumber));
      if (this.query.color) params.push("color=" + encodeURIComponent(this.query.color));
      if (this.query.status) params.push("status=" + encodeURIComponent(this.query.status));
   
     let param = params.join("&");
      // var param = "phone="+this.query.phone+"&nickname="+this.query.nickname+"&cardName="+this.query.cardName+"&serialNumber="+this.query.serialNumber
      toDownload(param).then(res => {
        downloadFile(res, '卡明细日志导出数据', 'xlsx')
        this.init()
      }).catch(err => {
        console.log(err.response.data.message)
      })
   },
   formatPoints(points) {
         return points / 10;
   },
   initProduct(){
      getList().then(res => {
         console.log(res)
         this.productList = res
     }).catch(err => {

     })
   },
   initUser(){
     getAllUserList().then(res => {
         console.log(res)
         this.userList = res
     }).catch(err => {

     })
   },

   submit(){
     this.loading = true
     if (this.isAdd) {
       this.doAdd()
     } else this.doEdit()
   },
   refresh(){
     this.dialog = false
     this.form = {
      id: '',
      businessName :"",
      status: 0,
      remark:""
     }
   },
   sendCode(){
       send().then(res => {
           console.log(res)
           this.form.serialNumber = res
       }).catch(err => {

       })
   },
   cancel(){
     this.refresh()
     this.init()
   },
    handleDateChange(value){

    },
   doAdd() {
     this.title = "新增"
     add(this.form).then(res => {
       this.refresh()
       this.$notify({
         title: '添加成功',
         type: 'success',
         duration: 2500
       })
       this.loading = false
       this.init()
     }).catch(err => {
       this.loading = false
       console.log(err.response.data.message)
     })
   },
   doEdit() {

     edit(this.form).then(res => {
       this.refresh()
       this.$notify({
         title: '修改成功',
         type: 'success',
         duration: 2500
       })
       this.loading = false
       this.init()
     }).catch(err => {
       this.loading = false
       console.log(err.response.data.message)
     })
   },
   subDelete(id){
     this.delLoading = true
     let ids = [id]
     del(ids).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
       this.init()
     }).catch(err => {
       this.loading = false
     })
   },
   edit(data) {
     this.title = "编辑"
     this.isAdd = false
     this.form = {
       id: data.id,
       title: data.title,
       japanese: data.japanese,
       serialNumber: data.serialNumber,
       levelFactoryDate: data.levelFactoryDate,
       color: data.color,
       status: data.status,
       remark: data.remark,
       userId:data.userId
     }
     this.dialog = true

   }
  }
}



</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
